import {Injectable, EventEmitter} from '@angular/core';
import { HttpInterceptorService } from './http-interceptor.service';
import {CanActivate, Router,ActivatedRouteSnapshot,RouterStateSnapshot,CanActivateChild} from '@angular/router';
import { Title } from '@angular/platform-browser';

import {$WebSocket, WebSocketSendMode} from './websocket.service';
import 'rxjs/add/operator/toPromise';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/debounceTime';

import { LoginService } from "../login/login.service";


@Injectable()

export class StorageService  implements CanActivate,CanActivateChild {

  private storage = window.localStorage;

  private permission:any;//权限数据

  private rights:any;//跟人信息总数据

  public isLogin:any;//跟人信息总数据

  public mask: any;//loading 遮罩dom

  public div: any;//loading 图片dom

  public img: any;//loading 图片dom

  public userInfo:object;//个人信息

  public userTypeCode:string;//员工code

  public menu:any;//菜单数据

  public redirectUrl: string;

  public btnRights:any ={};//权限数据

  public menuRights:any ={};//权限数据

  public dicData:any =[];//缓存的字典数据

  public orgData:any =[];//缓存的字典数据

  public messageService: EventEmitter<any>; //showmessage 事件传播；

  public makesureService: EventEmitter<any>; //确定取消弹窗 事件传播；

  public userinfoService: EventEmitter<any>; //用户信息更该 事件；

  public loadSubject = new Subject();//loading

  public eventbus :  EventEmitter<any>; // saas 组件事件 sidebar toggle event

  public getDataPromise:any;

  public unLoadfun: any;//取消取消订阅

  public debounceTime:number = 500;//防抖动时间

  constructor(private http: HttpInterceptorService, private router: Router, private loginService:LoginService, private titleService: Title) {
    this.creatLoadSubject();
    this.messageService = new EventEmitter();
    this.makesureService = new EventEmitter();
    this.userinfoService = new EventEmitter();
    this.eventbus = new EventEmitter();
    let dic = this.storage.getItem('dic');
    let org = this.storage.getItem('org');
    this.dicData = dic&&dic!='undefined'? JSON.parse(dic):null;
    this.orgData = org&&org!='undefined'?JSON.parse(org):null;
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.loginService.redirectUrl = state.url;
     return true;
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // console.log(route)
    // console.log(state)
    //   if(route.routeConfig && route.routeConfig.children){
    //     route.routeConfig.children.push(NewRoute)

    //     this.router.resetConfig([...this.router.config])
    //   }

/*     let routeData = route['_routeConfig'];
    if(!routeData.data || !routeData.data.authCode){return true}
    let right = this.menuRight(routeData.data.authCode);
    console.log(right)
    if(right){return true}else{
      this.router.navigate(['/noPrimise']);return false
    } */
    return true
  }

  checkLogin(url: string): boolean {
      this.loginService.redirectUrl = url;
      if (!this.loginService.isLogin && window.sessionStorage.getItem('isLogin') != 'true') {
          this.router.navigate(['/login']);
          return false;
      }
      return true;
  }

  //手动设置浏览器标题
  setBrowserTitle(title  = '家装综合运营管理平台'){
    this.titleService.setTitle(title)
  }

  //登录成功或刷新后获取数据
  getData(): Promise < any > {
      return Promise.resolve(this);
  }

  //获取字典数组
  getDic(str: string) {
      if (!str || !this.dicData) {
          return []
      }
      let dic = this.dicData.find(val => val.code == str);
      return dic ? dic.dictItems : [];
  }

  //字典过滤器
  dicFilter(dicName, dicCode) {
      let dics = this.getDic(dicName);
      if (!dics) {
          return ''
      }
      let man = dics.find(val => val.code == dicCode);
      return man ? man.name : '';
  }

  //组织结构过滤
  orgFilter(code) {
      let man = this.orgData.find(val => val.code == code);
      return man ? man.name : '';
  }

  btnRight(str) {
      if (!str) {
          return false
      }
      return this.btnRights[str]
  }

  menuRight(str) {
      if (!str) {
          return false
      }
      return this.menuRights[str]
  }

  getRights(): Promise < any > {
      if(this.getDataPromise){return this.getDataPromise }
      this.getDataPromise = new Promise(resolve => {
          if (this.menu) {
              resolve(this.getData());
          } else {
              this.http.post("sysRest/userInfo/api", {}).then(data => {
                  if (data.result) {
                      //标记已登录状态
                      this.loginService.isLogin = true;
                      this.isLogin = true;
                      //储存所有信息
                      this.rights = data.data;
                      //获取权限信息
                      this.permission = this.rights.permission || [];
                    //   this.bePermission();
                      //获取用户信息
                      this.userInfo = this.rights.user;
                      //获取员工信息
                      this.userTypeCode = this.rights.userTypeCode;
                      //获取菜单信息
                      this.menu = this.rights.authority;
                      resolve(this.getData());
                  } else {
                      this.isLogin = false;
                      this.rights = {};
                      this.loginService.isLogin = false;
                  }
              })
          }
      });
      return this.getDataPromise
  }

  bePermission() {
      this.menuRights = {};
      this.btnRights = {};
      this.permission.map(val => this[val.type == 2 ? 'btnRights' : 'menuRights'][val.code] = val.checked);
  }

  addMultipleClasses(element: any, className: string): void {
      if (element.classList) {
          let styles: string[] = className.split(' ');
          for (let i = 0; i < styles.length; i++) {
              element.classList.add(styles[i]);
          }
      } else {
          let styles: string[] = className.split(' ');
          for (let i = 0; i < styles.length; i++) {
              element.className += ' ' + styles[i]
          }
      }
  }

  openNew(url, post ? , otherUrl ? ) {
      let path = (post || this.http.baseUrl) + url;
      let a = document.createElement('a');
      a.href = otherUrl || path;
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
  }

  creatLoadSubject(){
    this.unLoadfun = this.loadSubject
    .debounceTime(this.debounceTime)
    .subscribe(e => this.loadFun(e));
  }

  loadFun(flag:any){
      if(flag){
        if (this.img || this.mask) {
            return
        }
        this.img = document.createElement('i');
        this.addMultipleClasses(this.img, 'fixed-center zindex-10001 fa fa-spinner fa-spin v-middle fa-2x color-333 opacity06');
        this.mask = document.createElement('div');
        this.mask.style.zIndex = 10000;
        this.addMultipleClasses(this.mask, 'ui-widget-overlay ui-dialog-mask');
        document.body.appendChild(this.img);
        document.body.appendChild(this.mask);
      }else{

        if (this.mask) {
            document.body.removeChild(this.mask);
            this.mask = null;
        }
        if (this.img) {
            document.body.removeChild(this.img);
            this.img = null;
        }
      }
  }


  loading(text ? ) {
     this.loadSubject.next(true);
  }

  loadout() {
    this.loadSubject.next(false);
  }

}
